package com.tmt.paymentcenter.web.configure.security.bean;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class TmtRegisterSessionAuthenticationStrategy extends RegisterSessionAuthenticationStrategy {

    private TmtClientSessionRegistry sessionRegistry;

    /**
     * @param sessionRegistry the session registry which should be updated when the
     *                        authenticated session is changed.
     */
    public TmtRegisterSessionAuthenticationStrategy(TmtClientSessionRegistry sessionRegistry) {
        super(sessionRegistry);
        this.sessionRegistry = sessionRegistry;
    }

    @Override
    public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Object token = request.getAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE);
        sessionRegistry.addSession(token, session, authentication);
        super.onAuthentication(authentication, request, response);
    }
}
